/*
 * PrintOrderLineRSDAO.java
 *
 * Created on April 6, 2007, 11:30 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.jjenkins.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
 * Contains all the CRUD methods which will use set and get objects to interact with the database
 * @author uni
 */
public class PrintOrderLineRSDAO extends RevenueSourceDAO{
    
    /**
     * singleton variable for PrintOrderLineRSDAO
     */
    private static PrintOrderLineRSDAO instance = null;
    
    /** Creates a new instance of PrintOrderLineRSDAO */
    private PrintOrderLineRSDAO() {
    }
    
    
    
    /**
     * This method implements the singleton pattern. It insures that only
     * on instance of InterestDAO exists
     * @return PrintOrderLineRSDAO
     */
    
    public static synchronized PrintOrderLineRSDAO getInstance() {
        if (instance == null) {
            instance = new PrintOrderLineRSDAO();
        }
        return instance;
    }
    
    
        /**
     * This method creates a new RevenueSourceBO with a unique QUID, puts the PrintOrderLIneRS
     * in cache, and then returns it to the calling method.
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return BAckup BO
     */
    
    public RevenueSourceBO create() throws DataException {
        try {
            
            String id = GUID.generate();
            RevenueSourceBO object = new PrintOrderLineRS(id);
            object.setId(id);
            Cache.getInstance().put(object.getId(), object);
            object.setType("Print Order");
            return object;
        } catch (Exception e) {
            throw new DataException("Could not create GUID", e);
        }
        
    }
    
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     * @param id id of PrintOrderLineRS
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return PrintOrderLineRS
     */
    public synchronized RevenueSourceBO read(String id) throws DataException {
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        PrintOrderLineRS object = (PrintOrderLineRS)cache.get(id);
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // If the item is not in cache a connection is checked out and
            // The item is read from the database.
            if(object == null){
                try {
                    //reads in object
                    object = (PrintOrderLineRS)read(id, conn);
                    
                }catch (SQLException e) {
                    conn.rollback();
                    throw new DataException("Could not retrieve record for id=" + id, e);
                }
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // Return object
        return object;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * @param id id of PrintOrderLineRS
     * @param conn connection
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return PrintOrderLineRS
     */
    synchronized RevenueSourceBO read(String id, Connection conn) throws SQLException, DataException {
        
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        PrintOrderLineRS object = (PrintOrderLineRS)cache.get(id);
        
        // Quieries that database
        if(object == null){
            
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM print_order_line WHERE print_line_guid = ?");
            pstmt.setString(1, id);
            pstmt.execute();
            ResultSet rs = pstmt.getResultSet();
            
            if (rs.next()) {
                object = new PrintOrderLineRS(id);
                object.setQuantity (rs.getInt ("quantity"));
                object.setDescription (rs.getString ("description"));
                object.setPhoto_set_guid (rs.getString ("photo_set_guid"));
                object.setPrint_format_guid (rs.getString ("print_format_guid"));
                
                
                // Sets already in database
                object.setObjectAlreadyInDB(true);
                
                // adds to cache
                cache.put(object.getId(), object);
                
                // Reads in RevenueSource details
                super.populateRevenueSource(object, conn);
                
            }else{
                throw new DataException("Object was not found in the database.");
            }
            
        }
        
        
        // returns object
        return object;
    }
    
    
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     * @param object PrintOrderLineRS
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    public synchronized void save(RevenueSourceBO object) throws DataException {
        try {
            
            
            // retrieve a database connection from the pool
            ConnectionPool connPool = ConnectionPool.getInstance();
            
            Connection conn = connPool.get();
            
            
            try {
                
                // Saves Interest
                save(object, conn);
                
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not save record for" + object.getId(), e);
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            // touch the cache for the object
            Cache.getInstance().touch(object.getId());
            
            
            
        } catch (DataException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (SQLException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        }
        
        
    }
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * 
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     * @param object PrintOrderLineRS
     * @param conn connection
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    synchronized void save(RevenueSourceBO object, Connection conn) throws SQLException, DataException {
        
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (object.isDirty()) {
            if (object.isObjectAlreadyInDB()) {
                super.update(object, conn);
                update(object, conn);
          
            }else{
                super.insert(object, conn);
                insert(object, conn);
            }
            object.setDirty(false);
        }
        
    }
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @param PrintOrderLineRS object
     */
    protected synchronized void insert(RevenueSourceBO object, Connection conn) throws SQLException, DataException {
        
        // Creates prepared statemetn
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO print_order_line VALUES(?, ?, ?, ?, ?)");
        pstmt.setString(1, object.getId());
        pstmt.setDouble(2, ((PrintOrderLineRS)object).getQuantity());
        pstmt.setString(3, ((PrintOrderLineRS)object).getDescription());
        pstmt.setString(4, ((PrintOrderLineRS)object).getPrint_format_guid());
        pstmt.setString(5, ((PrintOrderLineRS)object).getPhoto_set_guid());
        
        //Executes prepated statement
        pstmt.execute();
        
        //Sets already in database true
        object.setObjectAlreadyInDB(true);
        
    }
    
    /**
     * We intentionally do not allow a PrintOrderLineRS object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud.
     * @param object printorderline object to delete
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    
    public synchronized void delete(RevenueSourceBO object)throws DataException{
    /* We intentionally do not allow a PrintOrderLineRS object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud. */
        throw new DataException("You can not delete a PrintOrderLineRS");
    }
    
    
}
